package cn.quang.search.admin.service.common;

import cn.quang.search.common.utils.FastJsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisService {

    private static final String UNLOCK_LUA;
    static {
        UNLOCK_LUA = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
    }

    private static final Long RELEASE_SUCCESS = 1L;

    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    // 将String字符串写入缓存
    public String getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    // 从缓存中读取String字符串
    public void setString(String key, String value, long expireMillisecond) {
        stringRedisTemplate.opsForValue().set(key, value, expireMillisecond, TimeUnit.MILLISECONDS);
    }

    // 从缓存中读取String字符串并转换为实体
    public <T> T getEntity(String key, Class<T> clazz) {
        String jsonString = getString(key);
        if(StringUtils.isBlank(jsonString)) {
            return null;
        }
        return FastJsonUtils.jsonToBean(jsonString, clazz);
    }

    // 将实体转换成String字符串并写入缓存
    public <T> void setEntity(String key, T t, long expireMillisecond) {
        if(t != null) {
            String jsonString = FastJsonUtils.beanToJson(t);
            setString(key, jsonString, expireMillisecond);
        }
    }

    /**
     * 尝试加锁
     * @param key 锁的key
     * @param requestId 请求标识，用于释放锁时的校验
     * @param expireMillisecond 过期时间
     * @return true 加锁成功，false 加锁失败
     */
    public boolean tryLock(String key, String requestId, long expireMillisecond) {
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(key, requestId, expireMillisecond, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(result);
    }

    /**
     * 释放分布式锁
     * @param key 锁的key
     * @param requestId 请求标识，用于释放锁时的校验
     * @return 是否释放成功
     */
    public boolean releaseLock(String key, String requestId) {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(UNLOCK_LUA, Long.class);
        return RELEASE_SUCCESS.equals(stringRedisTemplate.execute(redisScript, Collections.singletonList(key), requestId));
    }
}